package com.brt.socket.rest.controller.socketConfig;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 推送警情的类
 * @author yuansili
 * */
public class SockJSServer {
	
	public static List<WebSocketSession> users =
			new CopyOnWriteArrayList<WebSocketSession>();
			//new ArrayList<WebSocketSession>();
	
//	public static String SEATNO = "SEATNO";
	
	private static Logger logger = Logger.getLogger("SockJSServer");
	
	/**
	 * 推送消息到某一IP
	 * @param ip
	 * @param jsonObject
	 * @throws Exception session closed
	 * @throws Exception can not find user
	 * @throws IOException
	 * 
	 * */
	public static void send(String ip,JSONObject jsonObject) throws Exception{
		
		logger.info("======>发送消息到客户端，ip : " + ip);

		TextMessage message = new TextMessage(jsonObject.toString());
		
		for(WebSocketSession session : users){
			if(session.isOpen()){
				synchronized (session) {
					if(ip.equals(session.getRemoteAddress().getAddress().getHostAddress())){
						logger.info("======>message : " + jsonObject.toString());
						session.sendMessage(message);
						return;
					}
				}
			}else{
				logger.warn("session is closed,ip : " + ip);
			}
		}
		//找不到session
		logger.warn("sockjs 发送组件找不到会话 : " + ip);
	}

}
